package com.xzjt.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzjt.common.exception.CustomException;
import com.xzjt.web.entity.SysRole;
import com.xzjt.web.entity.SysUser;
import com.xzjt.web.entity.SysUserRole;
import com.xzjt.web.mapper.SysMenuMapper;
import com.xzjt.web.mapper.SysRoleMapper;
import com.xzjt.web.mapper.SysUserMapper;
import com.xzjt.web.mapper.SysUserRoleMapper;
import com.xzjt.web.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @ClassName: SysUserServiceImpl
 * @Author: yuandong
 * @Date 2021/10/9 15:59
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;




    public List<SysUser> selectUserList(SysUser sysUser){
       return sysUserMapper.selectUserList(sysUser);

    }

    @Override
    public SysUser selectLoginUser(SysUser user) {
        SysUser sysUser = sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, user.getUsername()));
        return sysUser;
    }

    @Override
    public Page<SysUser> selectPage(Page<SysUser> page, QueryWrapper queryWrapper) {
        return sysUserMapper.selectPage(page, queryWrapper);
    }

    @Override
    public SysUser selectByUsername(String username){
        return sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
    }

    /**
     * 根据用户名获取用户信息(包括用户的角色和权限)
     * @param username
     * @return
     */
    public SysUser getByUserName(String username){

        //**查询用户
        SysUser sysUser = this.sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
        if(sysUser == null) return null;

        //查询角色
        sysUser.setRoles(this.sysRoleMapper.selectRolesByUserId(sysUser.getId()));


        //**查询权限
        List<SysRole> roles = sysUser.getRoles().stream().peek(role -> {
            //**admin角色包含所有权限
            if(role.getRoleCode().equals("admin"))
                role.setMenus(this.sysMenuMapper.selectList(new QueryWrapper<>()));
            else
                role.setMenus(this.sysMenuMapper.selectMenusByRoleId(role.getRoleId()));
        }).collect(toList());

        sysUser.setRoles(roles);

        return sysUser;
    }


    /**
     * 根据用户id 查询
     * @param userId
     * @return
     */
    @Override
    public SysUser selectById(Integer userId) {
        return null;
    }


    /**
     * 保存用户（并关联角色）
     * @param user
     * @return
     */
    @Override
    public int save(SysUser user) {
        user.setIsAdmin(2);
        user.setDel_flag(0);
        sysUserMapper.insert(user);

        //新增用户与角色(暂定一个用户只能选取一个角色)
        SysUserRole sysUserRole=new SysUserRole();
        sysUserRole.setRoleId(user.getRoleId());
        sysUserRole.setUserId(user.getId());
        int flag = userRoleMapper.insert(sysUserRole);

        return flag;
    }


    @Override
    public int updateUserById(SysUser user) {

        //1.先删除用户和角色的关联
        this.userRoleMapper.deleteUserRoleByUserId(user.getId());

        //2.重新建立用户和角色的关系
        SysUserRole sysUserRole=new SysUserRole();
        sysUserRole.setRoleId(user.getRoleId());
        sysUserRole.setUserId(user.getId());

        userRoleMapper.insert(sysUserRole);
        return sysUserMapper.updateById(user);
    }

    @Override
    public int checkUserNameUnique(String userName) {
        return sysUserMapper.checkUserNameUnique(userName);
    }


    /**
     * 用户重置密码
     * @param userId
     * @return
     */
    @Override
    public int resetPassword(Integer userId){

        SysUser sysUser=this.sysUserMapper.selectById(userId);
        String password = "123456";
        sysUser.setPassword(password);
        return  this.sysUserMapper.updateById(sysUser);
    }


    /**
     * 删除用户
     * @param userId
     * @return
     */
    public int  delUser(Integer userId){
        if(userId.equals(1)){
            throw new CustomException("不允许操作超级管理员用户");
        }

        //1:删除用户关联的角色
        return this.sysUserMapper.deleteById(userId);
    }


}
